package com.example.authorization_server.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static com.example.common.constant.Constant.MY_CLIENT_DETAIL_SERVICE;
import static com.example.common.constant.Constant.ResourceServerId.ORDER_SERVICE;

/**
 * @author 罗俊华
 * @date 2022/3/14 - 11:22 上午
 */
@Slf4j
@Service(MY_CLIENT_DETAIL_SERVICE)
public class ClientDetailServiceImpl implements ClientDetailsService {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {

        BaseClientDetails baseClientDetails = new BaseClientDetails();

        baseClientDetails.setClientId(clientId);

        baseClientDetails.setClientSecret(passwordEncoder.encode("1234"));

        List<SimpleGrantedAuthority> authorities = Arrays.asList("add", "del", "update", "query").stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());

//        设置权限
        baseClientDetails.setAuthorities(authorities);

//        设置权限范围
        baseClientDetails.setAutoApproveScopes(Collections.singletonList("order"));

//        设置 用户同意后，跳转的uri
        baseClientDetails.setRegisteredRedirectUri(Collections.singleton("https://www.baidu.com"));

//        可以访问的资源服务器列表，每一个资源服务器都有一个资源id
        baseClientDetails.setResourceIds(Collections.singleton(ORDER_SERVICE));


        // 此client 允许的授权类型
        baseClientDetails.setAuthorizedGrantTypes(Arrays.asList("password", "authorization_code", "client_credentials", "implicit", "refresh_token"));

        return baseClientDetails;
    }
}
